import JSEncrypt from 'jsencrypt'
import { Message, MessageBox } from 'element-ui' 
import UiMessage from './message'
class Utils {
    constructor() {
        this.step = 0, // 默认是标注页面
        this.returnUrl = '/user/member/task/mytask' // 返回页面url      
        this.$Message = Message
        this.$MessageBox = MessageBox
    }
    //获取链接后传参（单数据）
    getValue(key, cb) {
        var url = location.search;
        //判断是否存在key
        if (url.indexOf("?" + key + "=") != -1) {
            var val = url.substring(key.length + 2);
            cb(val);
        } else {
            cb("");
        }
    }
    //获取url参数
    getQueryStringArgs() {
        var qs = (location.search.length > 0 ? location.search.substring(1) : "");
        var args = {};
        var items = qs.split("&");
        var item = null,
            name = null,
            value = null;
        for (var i = 0; i < items.length; i++) {
            item = items[i].split("=");
            name = decodeURIComponent(item[0]);
            value = decodeURIComponent(item[1]);
            args[name] = value;
        }
        return args;
    }
    //截取字符串 value：被截取的字符串，len要截取的长度
    getSubString(value, len) {
        var r = "/[^\x00-\xff]/g"; //判断是否是中文
        if (value.replace(r, "mm").length <= len) {
            return value;
        }
        var m = Math.floor(len / 2);
        for (var i = m; i < value.length; i++) {
            if (value.substr(0, i).replace(r, "mm").length >= len) {
                return value.substr(0, i) + "...";
            }
        }
        return value;
    }
    setSession(key, value) {
        window.sessionStorage.setItem(key, JSON.stringify(value));
    }
    getSession(key) {
        return JSON.parse(window.sessionStorage.getItem(key));
    }
    setCookie(key, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = key + "=" + decodeURI(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/";
    }
    getCookie(key) {
        var cookieStr = document.cookie;
        if (cookieStr.length > 0) {
            var end, start = cookieStr.indexOf(key + "=");
            if (start != -1) {
                start = start + key.length + 1;
                end = cookieStr.indexOf(";", start);
                if (end == -1) end = cookieStr.length;
                return decodeURIComponent(cookieStr.substring(start, end));
            }
        }
        return ""
    }
    delCookie(key) {
        var expiredays = new Date();
        expiredays.setTime(expiredays.getTime() - 1);
        var _cookieVal = this.getCookie(key);
        if (_cookieVal != null) document.cookie = key + "=" + decodeURI(_cookieVal) + ";expires=" + expiredays.toGMTString() + ";path=/";
    }

    //RSA加密，例子参考login.vue
    RSAencrypt(data, flag) {
        let encryptor = new JSEncrypt();
        encryptor.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGUlARat3JCrdbnc54BDb+x1FKDBDHzfmZq3DZUWpPZ2xOpBDneBxCkdLB7b3k1SkihkWgOhty9TNAC7yPZ2+Sz2esZdqGT3z32Gjv2pbKH0Ngj0nvt5z8mXdi3FtkCF7tYFTzFfua4t8HSUNrDH0HixCy8q0/cpg6lhk7vE538wIDAQAB");
        let s = "";
        let n = 30;
        let f = data;
        if (typeof f == "object") {
            f = JSON.stringify(f);
        }
        if (flag) {
            if (f.length > n) {
                let len = Math.ceil(f.length / n);
                for (let i = 0; i < len; i++) {
                    if (i == len - 1) {
                        s += encryptor.encrypt(f.substr(i * n, n));
                    } else {
                        s = s + encryptor.encrypt(f.substr(i * n, n)) + ';';
                    }
                }
            } else {
                s = encryptor.encrypt(f);
            }
            return s;
        }
        return f;
    }
    /**
     * 跳转url
     * @param pUrl
     */
    jumpUrl(pUrl) {
        window.location.href = pUrl;
    }

    /**
     * 给url添加参数
     * @param pUrl
     * @param uriParam
     * @returns {string}
     */
    addUriParam(pUrl, uriParam) {
        var url = pUrl + '?';
        for (var key in uriParam) {
            url = url + key + '=' + uriParam[key] + '&';
        }
        return url;
    }
    /**
     * 缓存
     * @param key
     * @param value
     * @returns {*}
     */
    getsetCacheValue(id, value) {
        // 缓存处理
        var key = "markTask_history";
        var cache = window.localStorage.getItem(key);
        cache = this.isNull(cache) ? {} : JSON.parse(cache);
        var result = null;
        if (this.isNotNull(cache[id])) {
            result = cache[id].value;
        }
        // 没有变化也不进行操作
        if (this.isNull(value) || JSON.stringify(value) == JSON.stringify(result)) {
            return result;
        }
        cache[id] = {
            value: value,
            date: new Date().getTime()
        };
        let deleteKeys = [];
        for (let k in cache) {
            if (k != id && this.isNotNull(cache[k].date)) {
                let now = new Date().getTime();
                if (now - cache[k].date >= 7 * 24 * 60 * 60 * 1000) { // 超过7周，去除
                    deleteKeys.push(k);
                }
            }
        }
        for (let key in deleteKeys) {
            delete cache[key];
        }
        window.localStorage.setItem(key, JSON.stringify(cache));
        return result;
    }
    /**
     * 自适应 textarea高度
     * @param el
     * @param height
     */
    makeExpandingArea(el, height) {
        if (height == undefined) height = 'auto';
        el.style.height = height;
        el.style.height = (el.scrollHeight) + "px";
    }
    /**
     * 浏览器默认行为处理
     * @param e
     */
    shortkeyPreventAndBubble(e) {
        if (e && e.stopPropagation) {
            //使用W3C的stopPropagation()方法
            e.stopPropagation();
        } else {
            //使用IE的cancelBubble = true来取消事件冒泡
            window.event.cancelBubble = true;
        }
        if (e && e.preventDefault)
            //阻止默认浏览器动作(W3C)
            e.preventDefault();
        else {
            //IE中阻止函数器默认动作的方式
            window.event.returnValue = false;
        }
    }
    /**
     *   快捷键判断
     * @param isMatch
     * @param success
     * @param e
     */
    shortKeyIfTrue(isMatch, success, e) {
        if (isMatch) {
            success();
            this.shortkeyPreventAndBubble(e);
        }
    }
    /**
     * 将 s 转换 为固定时间格式
     * @param pTime
     * @param pPattern
     * @returns {*}
     */
    formatTime(pTime, pPattern) {
        if (isNaN(pTime) || pTime < 0) {
            return '--';
        }
        if (pPattern == 'HH:mm:ss') {
            return [('00' + Math.floor(pTime / 3600)).slice(-2), // hour
                ('00' + Math.floor(pTime % 3600 / 60)).slice(-2), // minutes
                ('00' + Math.floor(pTime % 60)).slice(-2)
            ].join(':'); // seconds
        } else if (pPattern == 'HH:mm:ss,SSS') {
            return [('00' + Math.floor(pTime / 3600)).slice(-2), // hour
                ('00' + Math.floor(pTime % 3600 / 60)).slice(-2), // minutes
                ('00' + Math.floor(pTime % 60)).slice(-2), // seconds
            ].join(':') + "," + ('000' + Math.floor(pTime * 1000 % 1000)).slice(-3); // ms;
        } else {
            return pTime;
        }
    }

    /**
     * 将时间转换为yyyy-MM-dd HH:mm:ss
     * @param pTime
     * @returns {string}
     */
    toDateTime(pTime) {
        var date = new Date(pTime),
            month = date.getMonth() + 1;
        month = month >= 10 ? month : '0' + month;
        var day = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate(),
            hours = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours(),
            minutes = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes(),
            seconds = date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds();
        return date.getFullYear() + '-' + month + '-' + day + ' ' +
            hours + ':' + minutes + ':' + seconds;
    }
    /**
     *  保留3位小数
     * @param pTime
     * @returns {number}
     */
    handleTime(pTime) {
        return Math.floor(pTime * 1000) / 1000;
    }
    /**
     * 获取元素在数组中的位置
     * @param arr
     * @param str
     * @returns {number}
     */
    indexOf(arr, str) {
        // 如果可以的话，调用原生方法
        if (arr && arr.indexOf) {
            return arr.indexOf(str);
        }
        var len = arr.length;
        for (var i = 0; i < len; i++) {
            // 定位该元素位置
            if (arr[i] == str) {
                return i;
            }
        }
        // 数组中不存在该元素
        return -1;
    }
    /**
     * 判断是否是json
     * @param str
     * @returns {boolean}
     */
    isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return true;
                } else {
                    return false;
                }
            } catch (e) {
                return false;
            }
        }
    }
    isNotNull(p) {
        if (p == undefined || p == null || p == 0 || p == '') {
            return false;
        }
        return true;
    }
    isNull(n) {
        if (n == undefined || n == null || n == '' || n == '--') {
            return true;
        }
        return false;
    }
    /**
     * 给指定的元素的指定位置添加焦点 textaera适用
     * @param pId
     * @param pPosition
     */
    skipFocusPosition(pId, pPosition) {
        var elem = document.getElementById(pId);
        elem.focus();
        if (elem.setSelectionRange) { // 标准浏览器
            elem.setSelectionRange(pPosition, pPosition);
        } else { // IE9-
            var range = elem.createTextRange();
            // range.moveStart("character", -len);
            // range.moveEnd("character", -len);  不知道哪里来的len by HuiNian
            range.moveStart("character", 0);
            range.moveEnd("character", 0);
            range.moveStart("character", pPosition);
            range.moveEnd("character", 0);
            range.select();
        }
    }
    prejudgeM(success) {
        var prejudeMethods = [];
        if (arguments.length > 1) {
            for (var i = 1; i < arguments.length; i++) {
                prejudeMethods.push(arguments[i]);
            }
        }
        return this.prejudgeMethodChain(prejudeMethods, success);
    }
    /**
     * 预先判断条件是否满足
     * @param success
     * @param prejudgeMethods
     */
    prejudgeMethodChain(prejudgeMethods, success) {
        var len = prejudgeMethods.length,
            isOk = true;
        for (var i = 0; i < len; i++) {
            if (prejudgeMethods[i] != undefined) {
                var result = prejudgeMethods[i]();
                if (result == undefined || result == false) {
                    isOk = false;
                    break;
                }
            }
        }
        if (isOk) {
            return success ? success() : null;
        }
    }
    closeResult(step) {
        if (step == undefined) step = 0;
        if (window.opener == null) {
            window.location.href = this.addUriParam(this.returnUrl, {
                tasktype: step
            });
        } else {
            // 跳转到父tab页并刷新
            window.opener.location.href = this.addUriParam(this.returnUrl, {
                tasktype: step
            });
            window.close();
        }
    }
    $alert_link(text, url) {
        MessageBox.alert(text, '操作提示', {
            confirmButtonText: '确定',
            callback: action => {
                location.href = url
            }
        })
    }
}

export const utils = new Utils()
export const uiMessage = UiMessage